// 引入vue
import Vue from 'vue'
// 引入路由
import VueRouter from 'vue-router'
// 导入子组件
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/users.vue'
import Right from '../components/power/Right.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Param from '../components/goods/Param.vue'
import List from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
import Report from '../components/report/Report.vue'
// 注册全局对象,可以在其他Vue组件中使用
Vue.use(VueRouter)

// 定义路由规则数组
const routes = [
  // 重定向
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    // 子路由
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Right },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Param },
      { path: '/goods', component: List },
      { path: '/goods/add', component: Add },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ]
  }
]

// 创建路由表对象实例
const router = new VueRouter({
  routes
})

// 设置路由守卫函数
// 作用：在浏览器地址栏的hash值发生改变时，可以检查当前访问的hash路径是否需要有token
// to:去哪个路由
// from:从哪个路由来
// next:是否放行
router.beforeEach((to, from, next) => {
  // 判断是否访问的为login，如果是，则放行
  if (to.path === '/login') {
    next()
  }
  // 否则，尝试获取内存中的token值
  const strToken = window.sessionStorage.getItem('token')
  // 如果没有token,则强制将hash改成/login
  if (!strToken) {
    return next('/login')
  }
  // 如果有token，则放行
  next()
})

// 导出路由表对象
export default router
